package com.oa.system.service.impl;

import com.oa.model.system.SysUser;
import com.oa.security.custom.CustomUser;
import com.oa.system.service.SysMenuService;
import com.oa.system.service.SysUserService;
import com.oa.security.custom.UserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author Admin
 * @title: UserDetailsServiceImpl
 * @projectName Cloud_OA_Office
 * @description: UserDetailsServiceImpl
 * @date 2024/10/10 20:56
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysMenuService sysMenuService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getByUserName(username);
        if(null == sysUser) {
            throw new UsernameNotFoundException("用户名不存在！");
        }

        if(sysUser.getStatus().intValue() == 0) {
            throw new RuntimeException("账号已停用");
        }
        //根据用户id查询用户权限列表
        List<String> userPermsList = sysMenuService.findUserPermsListByUserId(sysUser.getId());
        //创建List集合 封装最终权限数据
        List<SimpleGrantedAuthority> authList =
                new ArrayList<>();
        for(String perm : userPermsList) {
            authList.add(new SimpleGrantedAuthority(perm.trim()));
        }

        return  new CustomUser(sysUser, authList);
        //return new CustomUser(sysUser, Collections.emptyList());
    }
}
